package com.etc.controller;

import com.etc.domain.ZtreeResult;
import com.etc.entity.ProductCategory;
import com.etc.service.ProductCategoryService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品分类管理controller
 */
@RestController
@RequestMapping("/prodCat")
public class ProductCategoryController {
     //service接口的实例化对象
    @Autowired
    private ProductCategoryService pcs;

    /**
     * 返回前台需要的展示分类数据
     * @return ZtreeResult
     */
    @RequestMapping("/findAllProCat")
    public List<ZtreeResult> findAllProCat(){
        System.out.println("001");
        List<ZtreeResult> ztreeResultList = new ArrayList<>();
        List<ProductCategory> pcList = pcs.findAllProductCategory();
        //将ProductCategory转化为ZtreeResult的方法
        List<ZtreeResult> ztreeResultList1 = convertToZtreeResult(ztreeResultList, pcList);
        return  ztreeResultList1;
    }

    /**
     * 商品分类集合转换
     * @param ztreeResultList 前台展示用的分类集合(空)
     * @param pcList 后台查询得到的分类全部信息
     * @return 前台展示用的分类集合(实)
     */
    private List<ZtreeResult> convertToZtreeResult(List<ZtreeResult> ztreeResultList, List<ProductCategory> pcList) {

        for (ProductCategory productCategory:pcList){
            ZtreeResult zr = new ZtreeResult();
            zr.setId(productCategory.getId());
            zr.setpId(productCategory.getParentId());
            zr.setName(productCategory.getName());
            if(Long.valueOf(0).equals(productCategory.getParentId())){
                zr.setOpen(true);
            }
            ztreeResultList.add(zr);
        }

        return ztreeResultList;
    }
}
